package com.code.qgjx.controller.dealcontroller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.code.qgjx.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;
import com.code.qgjx.entity.User;
import com.code.qgjx.service.UserService;
import com.code.qgjx.tools.Layui;
import cn.hutool.crypto.SecureUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;

@Controller
@RequestMapping("/Sys")
@Api("学生信息管理相关api")
@Slf4j
public class UserController {
    
    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取用户列表
     *
     * @param limit 每页记录数
     * @param page 页码
     * @param role 用户角色
     * @return 返回用户列表和总记录数
     */
    @RequestMapping(value = "/getUserList")
    @ResponseBody
    public Object getUserList(@RequestParam("limit") String limit, @RequestParam("page") String page, @RequestParam("role") String role) {
        int lim = Integer.parseInt(limit);
        int start = (Integer.parseInt(page) - 1) * lim;
        List<User> user = userService.getUserList(role, null, start, lim);
        int total = userService.getUserCount(role, null);
        return JSON.toJSON(Layui.data(total, user));
    }

    /**
     * 添加新用户
     *
     * @param map 包含用户信息的Map对象
     * @return 添加成功返回"success"，否则返回"failure"
     */
    @RequestMapping(value = "/addUser")
    @ResponseBody
    public String addUser(@RequestBody Map<String, Object> map) {
        User user = new User();
        user.setUsername(map.get("username").toString());
        user.setPassword(SecureUtil.md5(map.get("password").toString()));
        user.setRole(map.get("role").toString());
        if (null != map.get("photo")){
            user.setPhoto(map.get("photo").toString());
        }
        if (map.get("name") != null){
            user.setName(map.get("name").toString());
        }else {
            user.setName("默认名称");
        }
        user.setPhone(map.get("phone").toString());
        user.setEmail(map.get("email").toString());
        if (map.get("timeSlot") != null){
            user.setTimeSlot(map.get("timeSlot").toString());
        }
        if (map.get("photo") != null) {
            user.setPhoto(map.get("photo").toString());
        }

        return userService.register(user) ? "success" : "failure";
    }

    /**
     * 修改用户密码
     *
     * @param map 包含用户名、密码和电话的Map对象
     * @return 修改成功返回"success"，否则返回"failure"
     */
    @RequestMapping(value = "/changePass")
    @ResponseBody
    public String changePass(@RequestBody Map<String, Object> map) {
        User user = new User();
        user.setUsername(map.get("username").toString());
        user.setPassword(SecureUtil.md5(map.get("password").toString()));
        user.setPhone(map.get("phone").toString());

        User byUsername = userMapper.findByUsername(user.getUsername());
        if (null != byUsername){
            if (!byUsername.getPhone().equals(user.getPhone())){
                return "failure";
            }
            byUsername.setPassword(user.getPassword());
            return userMapper.update(byUsername) > 0 ? "success" : "failure";
        }

        return "failure";
    }

    /**
     * 根据ID获取学生信息
     *
     * @param name 学生姓名，用于搜索
     * @param limit 每页记录数
     * @param role 用户角色
     * @param page 页码
     * @return 返回学生信息列表和总记录数
     */
    @ApiOperation("获取学生信息")
    @ApiResponses({
        @ApiResponse(code = 400, message = "请求参数没填好"),
        @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
    })
    @RequestMapping("/getStuById")
    @ResponseBody
    public String getStuById(@RequestParam("key[id]") String name,
                              @RequestParam("limit") String limit, @RequestParam("role") String role,
                              @RequestParam("page") String page) {
        int lim = Integer.parseInt(limit);
        int start = (Integer.parseInt(page) - 1) * lim;

        List<User> students;
        int total;

        if (name.equals("")) {
            students = userService.getUserList(role, null, start, lim);
            total = userService.getUserCount(role, null);
        } else {
            students = userService.getUserList(role, name, start, lim);
            total = userService.getUserCount(role, name);
        }

        return JSON.toJSONString(Layui.data(total, students));
    }

    /**
     * 删除多个用户
     *
     * @param nums 用户ID字符串，用逗号分隔
     * @return 删除成功返回"success"，否则返回"fail"
     */
    @RequestMapping("/deleteUsers")
    @ResponseBody
    public String deleteUsers(@RequestParam("nums") String nums) {
        String[] userIds = nums.split(",");
        boolean success = true;

        for (String id : userIds) {
            if (!id.isEmpty()) {
                success &= userService.deleteUser(Long.parseLong(id));
            }
        }

        return success ? "success" : "fail";
    }

    /**
     * 删除单个用户
     *
     * @param id 用户ID
     * @return 删除成功返回"success"，否则返回"fail"
     */
    @RequestMapping("/deleteUser")
    @ResponseBody
    public String deleteUser(@RequestParam("id") Long id) {
        return userService.deleteUser(id) ? "success" : "fail";
    }

    /**
     * 更新用户信息
     *
     * @param map 包含用户信息的Map对象
     * @return 更新成功返回"success"，否则返回"fail"
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public String updateUser(@RequestBody Map<String, Object> map) {
        User user = new User();
        user.setId(Long.parseLong(map.get("id").toString()));
        user.setUsername(map.get("username").toString());
        if (map.get("psw") != null) {
            user.setPassword(SecureUtil.md5(map.get("psw").toString()));
        }
        user.setName(map.get("name").toString());
        user.setEmail(map.get("email").toString());
        if (map.get("timeSlot") != null){
            user.setTimeSlot(map.get("timeSlot").toString());
        }
        if (map.get("photo") != null) {
            user.setPhoto(map.get("photo").toString());
        }
        if (map.get("phone") != null) {
            user.setPhone(map.get("phone").toString());
        }
        if (map.get("messagePush") != null) {
            user.setMessagePush((Boolean) map.get("messagePush"));
        }
        if (map.get("resume") != null) {
            user.setResume(map.get("resume").toString());
        }
        
        return userService.updateUser(user) ? "success" : "fail";
    }
}
